<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" width="26" src="@/assets/vue.svg"/>
        <a-typography-title :style="{ margin: 0, fontSize: '18px' }" :heading="5">
          {{ appStore.name }}
        </a-typography-title>
      </a-space>
      <!--  导航菜单    -->
      <Menu/>
    </div>
    <div></div>
    <ul class="right-side">
      <li></li>
      <li v-if="appStore.loginAuth">
        <a-dropdown trigger="click">
          <a-avatar v-if="userStore.isLogin" :size="32" :style="{ marginRight: '8px', cursor: 'pointer' }">
            <img alt="Avatar"
                 :src="baseUrl + userStore.avatar"
            />
          </a-avatar>
          <a-avatar v-else :size="32" :style="{ marginRight: '8px', cursor: 'pointer' }" @click="handleLogin">
            <span>登录</span>
          </a-avatar>
          <template v-if="userStore.isLogin" #content>
            <a-doption @click="goto('UserCenter')">
              <a-space>
                <icon-user/>
                <span>个人中心</span>
              </a-space>
            </a-doption>
            <a-doption @click="handleLogout">
              <a-space>
                <icon-export/>
                <span>退出登陆</span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>

    <!--  登录对话框  -->
    <a-modal v-model:visible="appStore.loginModal.visible"
             :mask-closable="false"
             :footer="false"
             title-align="start"
             :width="400"
             @cancel="modalCancelLogin"
    >
      <template #title>
        <div class="modal-login-title">
          <span class="modal-login-title__title">{{ modalSettingLogin.title }}</span>
          <span class="modal-login-title__ext">
            {{ formDataLogin.type === '0' ? '没有帐号？' : '已有帐号？' }}
            <a-link v-if="formDataLogin.type === '0'" @click="toRegister">点此注册</a-link>
            <a-link v-else @click="toLogin">点此登录</a-link>
          </span>
        </div>
      </template>

      <a-form ref="formRefLogin" :model="formDataLogin" :rules="rulesLogin" size="large"
              @submit-success="handleSubmitLogin">
        <a-form-item field="username" hide-label>
          <a-input v-model="formDataLogin.username" placeholder="请输入账号"/>
        </a-form-item>
        <a-form-item field="password" hide-label>
          <a-input-password v-model="formDataLogin.password" placeholder="请输入密码"/>
        </a-form-item>
        <a-form-item hide-label>
          <a-button type="primary" long html-type="submit">
            <span style="font-size: 16px">
              {{ formDataLogin.type === '0' ? '登录' : '立即注册' }}
            </span>
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';
import {useAppStore, useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {Message, Notification} from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import {encrypt} from '@/utils/jsencrypt';
import {LoginData, register} from "@/api/login/login.ts";
import Menu from '@/components/menu/index.vue';

const baseUrl = import.meta.env.VITE_API_BASE_URL;
const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();

// 遮罩
const {loading, setLoading} = useLoading();

const goto = (routeName: string) => {
  const {redirect, ...othersQuery} = router.currentRoute.value.query;
  router.push({
    name: (redirect as string) || routeName,
    query: {
      ...othersQuery,
    },
  });
}


/*登录-start*/
const handleLogin = () => {
  appStore.loginModal.visible = true;
  modalSettingLogin.onLoading = false;
}

const toRegister = () => {
  modalSettingLogin.title = '注册';
  formDataLogin.value.type = '1';
  resetLoginInfo();
}

const toLogin = () => {
  modalSettingLogin.title = '登录';
  formDataLogin.value.type = '0';
  resetLoginInfo();
}

const rulesLogin = {
  username: [
    {
      required: true,
      message: 'name is required',
    },
  ],
  password: [
    {
      required: true,
      message: 'password is required',
    },
  ],
}

const formRefLogin = ref();
const formDataLogin = ref({
  type: '0',
  username: '',
  password: ''
});

const resetFormDataLogin = () => {
  formRefLogin.value.clearValidate();
  formRefLogin.value.resetFields();
}

const resetLoginInfo = () => {
  formDataLogin.value.username = '';
  formDataLogin.value.password = '';
}

const modalSettingLogin = reactive({
  visible: appStore.loginModal.visible,
  onLoading: false,
  title: '登录'
});

const modalCancelLogin = () => {
  appStore.loginModal.visible = false;
  modalSettingLogin.onLoading = false;
  modalSettingLogin.title = '登录';
  resetFormDataLogin();

}

const handleSubmitLogin = async () => {
  if (loading.value) return;
  try {
    setLoading(true);
    if (formDataLogin.value.type === '1') {
      // 注册
      const params = JSON.parse(JSON.stringify(formDataLogin.value));
      const {code}: any = await register(params);
      if (code === 200) {
        Message.success({
          content: '注册成功'
        })
        resetFormDataLogin();
        appStore.loginModal.visible = false;
      }
    } else {
      // 登录
      const params: LoginData = {
        username: formDataLogin.value.username,
        password: encrypt(formDataLogin.value.password),
        types: ['user']
      }
      await userStore.login(params);
      userStore.updateSettings();
      const to = appStore.loginModal.to;
      await router.push({
        name: to || 'Home',
      });
      appStore.loginModal.visible = false;
      appStore.loginModal.to = "";
      resetFormDataLogin();

      Notification.success({
        content: '登录成功',
        duration: 1000
      });
    }
  } catch (err) {
    Notification.success((err as Error).message);
  } finally {
    modalSettingLogin.onLoading = false;
    setLoading(false);
  }

}
/*登录-end*/

// 退出登陆
const handleLogout = async () => {
  await userStore.logout()
  userStore.updateSettings();
  await router.push('Home');
};
</script>

<style scoped lang="less">
.navbar {
  display: flex;
  justify-content: space-between;
  height: 100%;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
}

.left-side {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.right-side {
  display: flex;
  padding-right: 20px;
  list-style: none;

  :deep(.locale-select) {
    border-radius: 20px;
  }

  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  a {
    color: var(--color-text-1);
    text-decoration: none;
  }

  .nav-btn {
    border-color: rgb(var(--gray-2));
    color: rgb(var(--gray-8));
    font-size: 16px;
  }

  .trigger-btn,
  .ref-btn {
    position: absolute;
    bottom: 14px;
  }

  .trigger-btn {
    margin-left: 14px;
  }
}
</style>

<style lang="less">
.message-popover {
  .arco-popover-content {
    margin-top: 0;
  }
}

.modal-avatar {
  text-align: center;
  margin-bottom: 20px;
}

.modal-login-title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;

  &__title {
    font-size: 20px;
  }

  &__ext {
    margin-right: 40px;
    font-size: 14px;
    font-weight: normal;
  }
}
</style>
